Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

362
Vistas
JavaScript: Parameter not passed to Array.forEach inside of the function => undefined?

const data = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  },
  "item" : [
    {
      "hello" : {
        "world" : "isHere"
      },
      "test" : "1"
    },
        {
      "hello" : {
        "world" : "isHere2"
      },
      "test" : "2"
    },
    ]
};

const iterate = (obj) => {
  
    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        let value = obj[key];
        let newObj = {[key]: value, 'style' : {backGroundColor : 'red'}};
        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

iterate(data);
console.log(data)

I have wrote a recursive function that should replace each key-value pair (not property!) with a object that i specify in the parameter.

However, if I use a array.forEach loop inside the function, the passed obj is undefined.

What am I missing?

Example


const iterate = (obj, newObj) => {

    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

However, if I define the object within the forEach, it works perfectly ....

const iterate = (obj) => {

    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        let value = obj[key];
        
        // SEE HERE
        let newObj = {[key]: value, 'style' : {backGroundColor : 'red'}};

        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

Why does the Object.keys(obj).forEach not see the passed parameter in the first version? And what is the solution?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to pass newObj whenever you call iterate inside the Array.forEach() - iterate(obj[key], newObj):

const data = {"desk":{"drawer":"stapler"},"cabinet":{"top drawer":{"folder1":"a file","folder2":"secrets"},"bottom drawer":"soda"},"item":[{"hello":{"world":"isHere"},"test":"1"},{"hello":{"world":"isHere2"},"test":"2"}]};

const iterate = (obj, newObj) => {
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') {
      iterate(obj[key], newObj)
    } else {
      // delete obj[key]; // remove for example purposes
      Object.assign(obj, newObj);
    }
  })
}

const newObj = {
  'style': {
    backGroundColor: 'red'
  }
};

iterate(data, newObj);
console.log(data)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda